package top.lingkang.finaloauth2.client.base;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lingkang
 * Created by 2022/3/23
 */
public class DefaultResourceExceptionHandler implements ResourceExceptionHandler {
    private static final Log log = LogFactory.getLog(DefaultResourceExceptionHandler.class);

    @Override
    public void permissionException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        printError(e, request, response);
    }

    @Override
    public void tokenInvalidException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        printError(e, request, response);
    }

    @Override
    public void exception(Exception e, HttpServletRequest request, HttpServletResponse response) {
        printError(e, request, response);
    }

    private void printError(Exception e, HttpServletRequest request, HttpServletResponse response) {
        // e.printStackTrace();
        log.warn(e.getMessage()
                + "  path=" + request.getServletPath());
        response.setContentType("text/html; charset=UTF-8");
        response.setStatus(200);
        try {
            response.getWriter().print("{\"code\": 1,\"msg\":\"" + e.getMessage() + "\",\"timestamp\":" + System.currentTimeMillis() + "}");
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}
